﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Timers;
using System.Windows.Forms;


namespace 自动关机Cmd
{
    public partial class Form1 : Form
    {
        private static bool m_isDateWork = false;
        private static DateTime m_stDateTime;
        private static string SAVE_KEY = @"SOFTWARE\ljm";
        public Form1()
        {
            InitializeComponent();
            DateTime dt = System.DateTime.Now;
            labTiem.Text = dt.ToString("yyyy年M月d日 HH:mm:ss");
            dtpDate.MinDate = dt;
            //dtpTime.MinDate = dt;
            dtpDate.Value = dt;
            dtpTime.Value = dt.AddHours(1);

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = 30000; //半分钟执行一次心跳
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(checkTime);

            string dateTime = getUserSetting("datetime");
            week_time.Value = DateTime.Parse(dateTime);
        }

        public static void createKeyIfNoExists(string key)
        {
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey hkSoftWare = hklm.OpenSubKey(key, true);
            if (hkSoftWare == null)
                hklm.CreateSubKey(key);
            hklm.Close();
            hkSoftWare.Close();
        }

        public static void saveUserSetting(string key, string value)
        {
            createKeyIfNoExists(SAVE_KEY);
            RegistryKey hklm = Registry.LocalMachine;
            RegistryKey hkSoftWare = hklm.OpenSubKey(SAVE_KEY, true);
            hkSoftWare.SetValue(key, value, RegistryValueKind.String);
            hklm.Close();
            hkSoftWare.Close();
        }

        public static string getUserSetting(string key)
        {
            string sValue = "";
            try
            {
                createKeyIfNoExists(SAVE_KEY);
                RegistryKey hklm = Registry.LocalMachine;
                RegistryKey hkSoftWare = hklm.OpenSubKey(SAVE_KEY, true);
                sValue = hkSoftWare.GetValue(key).ToString();
                hklm.Close();
                hkSoftWare.Close();
                return sValue;

            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
            }
            return sValue;
        }

        private static void checkTime(object source, ElapsedEventArgs e)
        {
            DateTime now = DateTime.Now;
            if (m_isDateWork&& m_stDateTime.Hour == now.Hour && m_stDateTime.Minute == now.Minute)
            {
                string cmd = "/s /t 1";
                Cmd(cmd);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt = System.DateTime.Now;
            labTiem.Text = dt.ToString("yyyy年M月d日 HH:mm:ss");

        }

        private void radioButton_Time_CheckedChanged(object sender, EventArgs e)
        {
            panelTime0.Enabled = rdbTime0.Checked;
            panelTime1.Enabled = rdbTime1.Checked;
        }

        private void btnEnter_Click(object sender, EventArgs e)
        {
            int time = 315360000;
            if (rdbTime0.Checked)
            {
                DateTime dt1 = System.DateTime.Now;
                DateTime dt2 = new DateTime(dtpDate.Value.Year, dtpDate.Value.Month, dtpDate.Value.Day, dtpTime.Value.Hour, dtpTime.Value.Minute, dtpTime.Value.Second);
                TimeSpan ts = dt2.Subtract(dt1);
                if (ts.TotalSeconds < 0)
                {
                    MessageBox.Show("时间设置异常!");
                    return;
                }
                time = (int)ts.TotalSeconds;
            }
            else if (rdbTime1.Checked)
            {
                time = (int)nudHour.Value * 60 + (int)nudMin.Value;
                time *= 60;
            }
            else if (radioWeekTime.Checked)
            {
                //每日定时执行
                m_isDateWork = true;
                m_stDateTime = week_time.Value;
                saveUserSetting("datetime", m_stDateTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            String cmd = "";
            if (rabShutdown0.Checked)
            {
                cmd = @"/s";
            }
            else if (rabShutdown1.Checked)
            {
                cmd = @"/r";
            }
            else if (rabShutdown2.Checked)
            {
                cmd = @"/l";
            }
            else if (rabShutdown3.Checked)
            {
                cmd = @"/h";
            }
            cmd += @" /t " + time;
            Console.WriteLine(cmd);
            Cmd(cmd);

        }


        private void btnCancel_Click(object sender, EventArgs e)
        {
            string code = this.txt_code_cancle.Text;
            if (code == "112255")
            {
                this.txt_code_cancle.Text = "";
                Cmd(@"/a");

            }
            else if (String.IsNullOrEmpty(code))
            {
                MessageBox.Show("请输入取消密码");
            }
            else
            {
                MessageBox.Show("当前密码错误");
            }
        }

        private void dtpDate_ValueChanged(object sender, EventArgs e)
        {
            //dtpTime.Value

        }


        public static String Cmd(String cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "shutdown";           //设定程序名   
            p.StartInfo.Arguments = cmd;// folderpath; //ls命令  foldername:"storage/emulated/0"
            p.StartInfo.UseShellExecute = false;        //关闭Shell的使用   
            p.StartInfo.RedirectStandardInput = true;   //重定向标准输入   
            p.StartInfo.RedirectStandardOutput = true;  //重定向标准输出   
            p.StartInfo.RedirectStandardError = true;   //重定向错误输出   
            p.StartInfo.CreateNoWindow = true;          //设置不显示窗口   
            p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
            p.Start();

            String result = p.StandardOutput.ReadToEnd();
            String error = p.StandardError.ReadToEnd();
            p.Close();
            return result + ";" + error;
        }

        private void radioWeekTime_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void week_time_ValueChanged(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string path = Application.ExecutablePath;
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            rk2.SetValue("JcShutdown", path);
            rk2.Close();
            rk.Close();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            string path = Application.ExecutablePath;
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey rk2 = rk.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run");
            rk2.DeleteValue("JcShutdown", false);
            rk2.Close();
            rk.Close();
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
